<template>
  <n-card :bordered="false" class="proCard">
    <!--表单部分,可以动态创建表单-->
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <!--展示信息部分-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row:ListData) => row.projectId"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="showUserdrawer" style="margin-right: 10px">
          <!--“+”号图标
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>-->
          新建
        </n-button>
      </template>
      <template #deletedata>
        <n-button type="primary" :disabled="isRowKeysEmpty" @click="batchDelete"> 删除 </n-button>
      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-drawer v-model:show="showdrawer" :width="600">
      <n-drawer-content :title="titledrawer" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="项目名称" path="projectName">
              <n-input placeholder="请输入项目名称" v-model:value="formParams.projectName" clearable="true" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="项目地址" path="projectAddress">
              <n-input placeholder="请输入项目地址" v-model:value="formParams.projectAddress" clearable="true"/>
            </n-form-item-gi>
          </n-grid>
        </n-form>
        <template #footer>
          <n-button type="primary" @click="saveuserinfo"> 提交 </n-button>
        </template>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, toRefs, unref, watch, computed } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    getTableList,
    batchDelProject,
    createProject,
    updateProject,
    getEditInit,
  } from '@/api/project/project';
  import { addUser } from '@/api/user/modal';
  import { columns, ListData } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { useRouter, useRoute } from 'vue-router';
  import { type FormRules } from 'naive-ui';
import { get } from '@vueuse/core';


  const schemas: FormSchema[] = [
    {
      field: 'searchValue',
      component: 'NInput',
      label: '快速查询',
      componentProps: {
        placeholder: '请输入项目名称',
        onInput: (e: any) => {
          // console.log('searchValue', e);
        },
      },
      rules: [{ required: false, message: '请输入项目名称', trigger: ['blur'] }],
    },
  ];
  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    schemas,
    showAdvancedButton: false,
  });

  const router = useRouter();
  const route = useRoute();
  const formRef: any = ref(null);
  const actionRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);


  const showdrawer = ref(false);
  const titledrawer = ref('');
  const rules: FormRules = {
    projectName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入项目名',
    },
    projectAddress: [{ required: false, trigger: ['blur', 'input'], message: '请输入项目地址' },],
  };

  const formParams = reactive({
    projectName: '',
    projectAddress: '',
    projectId: '',
  });

  function showUserdrawer() {
    showdrawer.value = true;
    titledrawer.value = '新建项目';
    formParams.projectName = '';
    formParams.projectAddress = '';
  }

  const editInitParams = ref({});
  // cdx：表格里面的编辑按钮对应的函数
  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    editInitParams.value = await getEditInit({ projectID: record.projectId });
    console.log('init parmas:', editInitParams.value);
    showdrawer.value = true;
    titledrawer.value = '编辑项目';
    formParams.projectName = editInitParams.value.projectName;
    formParams.projectAddress = editInitParams.value.projectAddress;
    formParams.projectId = editInitParams.value.projectId;
  }

  function saveuserinfo() {
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        if (titledrawer.value == "编辑项目") {
          // 编辑用户
          const params = formParams;
          console.log('修改', formParams);
          await updateProject(params);
          window['$message'].success('编辑成功');
        } else {
          // 创建用户
          const params = formParams;
          await createProject(params);
          window['$message'].success('新建成功');
        }
        setTimeout(() => {
          showdrawer.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请输入完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  // 数据表格部分的actionColumn
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            // auth: ['basic_list'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
        ],
        dropDownActions: [
          {
            label: '启用',
            key: 'enabled',
            // 根据业务控制是否显示: 非enable状态的不显示启用按钮
            ifShow: () => {
              return true;
            },
          },
          {
            label: '禁用',
            key: 'disabled',
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          window['$message'].info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  // 加载数据表
  const loadDataTable = async (res) => {
    const data = await getTableList({ ...getFieldsValue(), ...res });
    console.log('loadDataTableRes:', data);
    return data;
  };

  //cdx：其他地方使用rowKeys，需要将其定义为一个响应式变量
  const rowKeys = ref([]);
  function onCheckedRow(rKeys) {
    console.log('选中的行数据', rKeys);
    rowKeys.value = rKeys;
    console.log('rowKeys.value', rowKeys.value.length);
  }

  //cdx：控制删除按钮是否可以点击，计算选中数据list的length是否为0。奇怪的是，直接在组件绑定“rowKeys.value.length === 0”会报错，转换为计算属性即可
  const isRowKeysEmpty = computed(() => {
    return rowKeys.value.length === 0;
  });

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e) {
    console.log('新建信息：', formParams);
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('新建信息：', formParams);
        window['$message'].success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  async function handleDelete(record: Recordable) {
    console.log('单挑删除的数据', [record.userId]);
    try {
      const res = await batchDelProject({ delProjectList: [record.projectId] });
      window['$message'].info('点击了删除');
      reloadTable();
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('DelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
  // cdx：表格上方的批量删除按钮对应的函数
  async function batchDelete() {
    console.log('批量删除的数据2:', rowKeys.value);
    try {
      const res = await batchDelProject({ delProjectList: rowKeys.value });
      window['$message'].info('点击了删除');
      reloadTable();
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('batchDelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    reloadTable();
  }
</script>

<style lang="less" scoped></style>
